﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.VisualBasic;
using System.Xml;

namespace kwzx
{
    public partial class XMLAPI : Form
    {
        private static XMLAPI defaultInstance;

        /// <summary>
        /// Added by the VB.Net to C# Converter to support default instance behavour in C#
        /// </summary>
        public static XMLAPI Default
        {
            get
            {
                if (defaultInstance == null)
                {
                    defaultInstance = new XMLAPI();
                    defaultInstance.FormClosed += new FormClosedEventHandler(defaultInstance_FormClosed);
                }

                return defaultInstance;
            }
        }

        static void defaultInstance_FormClosed(object sender, FormClosedEventArgs e)
        {
            defaultInstance = null;
        }
        public XMLAPI()
        {
            InitializeComponent();
            //Added to support default instance behavour in C#
            if (defaultInstance == null)
                defaultInstance = this;

            // Add any initialization after the InitializeComponent() call.
            ObjSpread.StartConnect();

            SpreadGroup.Text = "PC201212151543";// (new Microsoft.VisualBasic.Devices.Computer()).Name;
            Message.Text = "<perform><cmd>DisplayMessage</cmd><param><query><Param1> Hi, How are you? </Param1></query></param></perform>";

            Timer1.Enabled = true;


            ObjSpread.ExceptionHappen += new Spread.ExceptionHappenEventHandler(ObjSpread_ExceptionHappen);
            ObjSpread.SpreadPollingError += new Spread.SpreadPollingErrorEventHandler(ObjSpread_SpreadPollingError);
            ObjSpread.MessageArrive += new Spread.MessageArriveEventHandler(ObjSpread_MessageArrive);
        }
        private Collection ColMessage = new Collection();

        private Spread ObjSpread = new Spread();

        [DllImport("Kernel32", EntryPoint = "OutputDebugStringA", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)]
        public static extern void OutputDebugString(string lpBuffer);

        string strrp = "";
        delegate void SetTextCallback(string text, TextBox tbx, string j);
        private void SetText(string text, TextBox tbx, string j)
        {
            if (tbx.InvokeRequired)
            {

                this.Invoke(new SetTextCallback(SetText), new object[] { text, tbx, j });  //

                //SetTextCallback d = new SetTextCallback(SetText(text));
                //this.Invoke(d, new object[] { text });
            }
            else
            {
                if (!tbx.Text.Contains(text))
                {
                    if (j == "+")
                        tbx.Text += "\r\n" + text;
                    if (j == "=")
                        tbx.Text = text;
                }
            }


        }
        public void WriteOnLog(string St)
        {
            strrp += St + "\r\n";
            this.Received.Text = strrp;
        }

        public void ObjSpread_ExceptionHappen(string FunctionName, System.Exception ex)
        {
            WriteOnLog((string)(" ObjSpread_ExceptionHappen " + FunctionName + " " + ex.Message));
        }


        public void ObjSpread_SpreadPollingError(int r)
        {
            WriteOnLog(" ObjSpread_SpreadPollingError " + r.ToString());
        }

        public void ObjSpread_MessageArrive(string Message)
        {
            try
            {
                //WriteOnLog(Message)
                ColMessage.Add(Message, null, null, null);
            }
            catch (Exception)
            {
                OutputDebugString((string)(DateTime.Now + " ObjSpread_MessageArrive Exception !!!" + "\r\n"));
                WriteOnLog((string)(DateTime.Now + " ObjSpread_MessageArrive Exception !!!"));
            }

        }
        private void CmdSendToSpread_Click(object sender, EventArgs e)
        {
            ObjSpread.SpreadSend(SpreadGroup.Text, Message.Text);
        }
        string[,] tname = { { "cmd", "命令", "" }, { "ID", "记录选择编号", "" }, { "mDate", "时间", "" }, { "Trn_Type", "类型", "" }, { "From_Name", "读卡器名称", "" }, { "Desc1", "交换代码", "" }, { "Desc2", "拒绝原因", "" }, { "Desc3", "姓名/卡号", "" }, { "Reader", "读卡器编号", "" }, { "mInput", "护卫", "" }, { "Controller", "控制器编号", "" }, { "Cardholder", "卡编号", "" }, { "User", "", "" }, { "Soc", "", "" }, { "Soc2", "", "" }, { "CH_Trans", "", "" }, { "Acknowledged", "", "" }, { "Confirmed", "", "" }, { "tmpStyle", "", "" }, { "NoLogHistory", "", "" }, { "EmpPhoto", "照片的文件名", "" }, { "isDoorContact", "", "" }, { "isRTX", "", "" }, { "DoorName", "", "" }, { "CameraID", "", "" }, { "EmpType", "", "" } };
        //解析XML
        private string[,] xmlst(string str)
        {
            try
            {


                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(str);
                XmlElement root = xmlDoc.DocumentElement;
                XmlNodeList perform = root.GetElementsByTagName("perform");

                XmlNodeList cmd = root.GetElementsByTagName("cmd");


                if (cmd.Count > 0)
                {

                    string cmdstr = ((XmlElement)cmd.Item(0)).InnerText;
                    tname[0, 2] = cmdstr;
                    if (cmdstr == "TreatEvent")
                    {//<query>

                        for (int i = 1; i < tname.Length; i++)
                        {
                            string kj = tname[i, 0].ToString();
                            XmlNodeList cmdi = root.GetElementsByTagName(kj);
                            tname[i, 2] = ((XmlElement)cmdi.Item(0)).InnerText;
                            //
                        }
                    }
                }
                return tname;

            }
            catch (Exception ex)
            {
                return tname;

            }
        }
        private void Button1_Click(object sender, EventArgs e)
        {
            Received.Text = "";
        }
        //抓拍处理    string[,] tname = { { "cmd", "命令", "1" }, { "ID", "记录选择编号", "2" }, { "mDate", "时间", "3" }, { "Trn_Type", "类型", "4" }, { "From_Name", "读卡器名称", "5" },
        //{ "Desc1", "交换代码", "6" }, { "Desc2", "拒绝原因", "7" }, { "Desc3", "姓名/卡号", "8" }, { "Reader", "读卡器编号", "9" }, { "mInput", "护卫", "10" }, 
        //{ "Controller", "控制器编号", "11" }, { "Cardholder", "卡编号", "12" }, { "User", "", "13" }, { "Soc", "", "14" }, { "Soc2", "", "15" }, { "CH_Trans", "", "16" },
        //{ "Acknowledged", "", "17" }, { "Confirmed", "", "18" }, { "tmpStyle", "", "19" }, { "NoLogHistory", "", "20" }, { "EmpPhoto", "照片的文件名", "21" },
        //{ "isDoorContact", "", "22" }, { "isRTX", "", "23" }, { "DoorName", "", "24" }, { "CameraID", "", "25" }, { "EmpType", "", "26" } };

        //门ID

        //当前门的控制器ID
        string kzqid = "";
        //进入读卡器
        string dkqid = "";



        private bool ryzp(string[,] skjl)
        {

            if (skjl[0, 2] == "TreatEvent")
            {
                string kzq = "-" + skjl[11, 2] + "-";
                //判断控制是否在这个门下
                if (kzqid.Contains("kzq"))
                {
                    string dkq = "-" + skjl[9, 2] + "-";
                    //读卡器编号 判断是否是进门，只有进门抓拍
                    if (dkqid.Contains(dkq))
                    {
                        //时间
                        string sj = skjl[9, 2].ToString().Replace(":", "").Replace(" ", "");
                        //文件名
                        string wjm = kzq.Replace("-", "") + "-" + dkq.Replace("-", "") + "-" + sj + ".jpg";
                        //抓拍方法
                        //skjl[0, 12]//卡编号
                    }

                }

            }
            return true;
        }


        DateTime newdt = DateTime.Now;
        private void Timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                while (ColMessage.Count > 0)
                {
                    string st;
                    st = ColMessage[1].ToString();

                    string[,] bjv = xmlst(st);
                    bool zpcg = ryzp(bjv);

                    SetText(st, Received, "+");
                    //WriteOnLog(st);
                    ColMessage.Remove(1);

                    newdt = DateTime.Now;
                }
                double len = (DateTime.Now - newdt).TotalMinutes;
                if (len > 1.2)
                {//1分20秒没收到数据或心跳包就重联服务
                    newdt = DateTime.Now;
                    ObjSpread.StartConnect();

                }

            }
            catch (Exception ex)
            {
                //	OutputDebugString((string) (DateTime.Now+ " Timer1_Tick Exception !!!" + "\r\n"));
                WriteOnLog((string)(DateTime.Now + " Timer1_Tick Exception !!!"));
            }
        }

        private void XMLAPI_Load(object sender, EventArgs e)
        {

        }
    }
}
